package com.trytech.mongoocrawler.server.transport.handler;

import com.trytech.mongoocrawler.common.transport.protocol.AbstractProtocol;
import com.trytech.mongoocrawler.common.transport.protocol.CommandProtocol;
import com.trytech.mongoocrawler.common.transport.protocol.HtmltextProtocol;
import com.trytech.mongoocrawler.common.transport.protocol.ProtocolFilterChain;
import com.trytech.mongoocrawler.server.CrawlerContext;
import com.trytech.mongoocrawler.server.DistributedCrawlerSession;

/**
 * @author jiangtao@meituan.com
 * @since: Created on 2018年07月01日
 */
public class HtmltextProtocolHandler extends ServerProtocolHandler {

    public HtmltextProtocolHandler(CrawlerContext crawlerContext) {
        super(crawlerContext);
    }

    @Override
    protected AbstractProtocol doHandle(ProtocolFilterChain filterChain, AbstractProtocol protocol) throws Exception {
        //获取url对应的session
        DistributedCrawlerSession crawlerSession = (DistributedCrawlerSession) crawlerContext.getSession(protocol.getSessionId());
        //解析爬取数据
        crawlerSession.parse(((HtmltextProtocol) protocol));
        //通知客户端可以继续发送命令
        CommandProtocol commandProtocol = new CommandProtocol();
        commandProtocol.setCommand(CommandProtocol.Command.CONTINUE);
        commandProtocol.setTraceId(protocol.getTraceId());
        return commandProtocol;
    }

    @Override
    protected boolean checkProtocol(AbstractProtocol abstractProtocol) {
        return abstractProtocol instanceof HtmltextProtocol;
    }
}
